package net.sf.ivyide.idea;

import com.intellij.openapi.progress.ProgressIndicator;
import fr.jayasoft.ivy.ModuleId;

import java.io.File;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

public class ModuleResolver {

    public List<ResolvedModule> getResolvedModules(final IvyProjectSettings settings, ProgressIndicator indicator) {
        indicator.setIndeterminate(false);
        indicator.setFraction(0.1);
        indicator.setText("Resolving modules");
        indicator.setText2("root module");
        double maxResolves = settings.getAmountOfSourceModules() + 1;//also include root module
        double resolvedCount = 0;
        ResolvedModule rootModule = new ResolvedModule(settings);
        indicator.setFraction(++resolvedCount / maxResolves);
        List<ResolvedModule> results = new LinkedList<ResolvedModule>();
        results.add(rootModule);
        Map<ModuleId, DependencyType> internalModules = rootModule.getInternalModules();
        for (ModuleId moduleId : internalModules.keySet()) {
            if (DependencyType.SOURCE.equals(internalModules.get(moduleId))) {
                final File file = settings.m_environmentInfo.getModules().get(moduleId);
                indicator.setText2(moduleId.getName());
                ResolvedModule resolvedModule = new ResolvedModule(settings.m_environmentInfo, file, settings.m_moduleDependencies);
                resolvedModule.checkResolveReport();
                results.add(resolvedModule);
                indicator.setFraction(++resolvedCount / maxResolves);
            }
        }
        Collections.sort(results);
        Collections.reverse(results);
        indicator.setIndeterminate(true);
        indicator.setText2("");
        return results;
    }

}
